package model

import (
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"tapay-bot/global"
	"tapay-bot/pkg/util"
	"time"
)

type ErrorLog struct {
	ID        uint32 `gorm:"primary_key" json:"id"`
	FuncName  string `json:"func_name"`  //方法名称
	DependId  uint32 `json:"depend_id"`  //依赖ID例如：orderID
	SelectKey string `json:"select_key"` //关键字查询
	Params    string `json:"params"`     // 入参
	Content   string `json:"content"`    //内容
	CreatedOn uint32 `json:"created_on"`
}

func (o ErrorLog) TableName() string {
	return "base_error_log"
}

func (o *ErrorLog) Create(db *gorm.DB) {

	o.CreatedOn = uint32(time.Now().Unix())
	err := db.Create(o).Error
	if err != nil {
		global.Logger.Errorf(context.Background(), "errorLog.Create() err:%v", err)
	}
}

func (o ErrorLog) CreateErrLog(db *gorm.DB, dependId uint32, funcName string, params interface{}, err error) {
	if len(funcName) == 0 {
		return
	}
	o.DependId = dependId
	o.FuncName = funcName
	if params != nil {
		if str, ok := params.(string); ok {
			o.Params = str
		} else {
			o.Params = util.StructToJsonStr(params)
		}
	}
	o.Content = err.Error()
	o.Create(db)
}
func (o ErrorLog) CreatePanicErrLog(db *gorm.DB, dependId uint32, funcName string, params interface{}, content string) {
	o.DependId = dependId
	o.FuncName = funcName
	if params != nil {
		if str, ok := params.(string); ok {
			o.Params = str
		} else {
			o.Params = util.StructToJsonStr(params)
		}
	}
	o.Content = content
	o.Create(db)
}

func (o ErrorLog) CreateErrLog2(db *gorm.DB, dependId uint32, funcName string, params interface{}, errMsg, selectKey string) {
	o.DependId = dependId
	o.FuncName = funcName
	if params != nil {
		if str, ok := params.(string); ok {
			o.Params = str
		} else {
			o.Params = util.StructToJsonStr(params)
		}
	}
	o.SelectKey = selectKey
	o.Content = errMsg
	o.Create(db)
}

func (o *ErrorLog) CreateWithError(db *gorm.DB) (err error) {
	o.CreatedOn = uint32(time.Now().Unix())
	return db.Create(o).Error
}

func (o *ErrorLog) UpdateContentForInviteLoop(db *gorm.DB) (err error) {
	data := map[string]interface{}{
		"content": gorm.Expr("CONCAT(content, ?)", o.Content),
	}
	result := db.Table(o.TableName()).Where("id = ?", o.ID).Updates(data)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected != 1 {
		return errors.New(fmt.Sprintf("update error log content for invite loop err, log id: %d, content: %s", o.ID, o.Content))
	}
	return nil
}
